package com.fenghuajueli.lib_ad;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConfig;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTCustomController;
import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.bytedance.sdk.openadsdk.TTSplashAd;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 广告显示工具
 */
public class AdShowUtils {


    private static final String LOAD_CHAPIN = "LOAD_CHAPIN";
    private static final String LOAD_BANNER = "LOAD_BANNER";
    private static final String TAG = "AdShowUtils";

    private static volatile AdShowUtils instance;
    private static SharedPreferences sharedPreferences;
    private Context context;
    private boolean mHasShowDownloadActive = false;
    private AdConfig adConfig;

    //每次重新启动时 插屏广告不受显示逻辑的控制，必然弹出
    public boolean isLauncherLoadChaPinAd = true;
    public boolean isLauncherLoadBannerAd = true;
    /**
     * 存放各个页面展示的banner广告，在界面销毁时 广告需要销毁
     * key为当前广告页的tag 一定不能相同 ，不然TTNativeExpressAd对象被替换
     * 然后没有销毁，防止activity内存泄漏
     */
    private final Map<String, TTNativeExpressAd> bannerMap = new HashMap<>();
    /**
     * 存放各个页面展示的插屏广告，在界面销毁时 广告需要销毁
     * key为当前广告页的tag 一定不能相同 ，不然TTNativeExpressAd对象被替换
     * 然后没有销毁，防止activity内存泄漏
     */
    private final Map<String, TTNativeExpressAd> interactionAdMap = new HashMap<>();

    public static AdShowUtils getInstance() {
        if (instance == null) {
            synchronized (AdShowUtils.class) {
                if (instance == null) {
                    instance = new AdShowUtils();
                }
            }
        }
        return instance;
    }


    private AdShowUtils() {

    }


    /**
     * 判断广告是否初始化成功
     *
     * @return
     */
    public boolean isInitSuccess() {
        return TTAdSdk.isInitSuccess();
    }

    /**
     * 初始化本地存储
     */
    private void initSharedPreferences() {
        sharedPreferences = context.getSharedPreferences("AD_CONFIG_INFO", Context.MODE_PRIVATE);
    }


    /**
     * 获取当前的广告配置
     *
     * @return
     */
    public AdConfig getAdConfig() {
        return adConfig;
    }

    /**
     * 初始化穿山甲广告sdk
     *
     * @param context
     * @param isDebug  是否是debug环境
     * @param adConfig 广告位相关信息
     */
    public void initAdConfig(Application context, Boolean isDebug, AdConfig adConfig) {
        this.context = context;
        if (adConfig == null) {
            throw new NullPointerException("adConfig Cannot be empty，please init adConfig");
        }
        this.adConfig = adConfig;
        initSharedPreferences();
        TTAdConfig.Builder builder = new TTAdConfig.Builder()
                .appId(adConfig.getAdAppId())
                .useTextureView(false) //使用TextureView控件播放视频,默认为SurfaceView,当有SurfaceView冲突的场景，可以使用TextureView
                .allowShowNotify(true) //是否允许sdk展示通知栏提示
                .allowShowPageWhenScreenLock(true) //是否在锁屏场景支持展示广告落地页
                .debug(isDebug) //测试阶段打开，可以通过日志排查问题，上线时去除该调用
                .supportMultiProcess(false) //是否支持多进程，true支持
                .customController(new TTCustomController() {
                    @Override
                    public boolean isCanUsePhoneState() {
                        return Build.VERSION.SDK_INT < Build.VERSION_CODES.Q;
                    }
                });
        if (adConfig.isEnablePopDialogWithAd()) {
            builder.directDownloadNetworkType();
            Log.d(TAG, "------------------------广告启用下载弹窗-------------------------");
        } else {
            builder.directDownloadNetworkType(TTAdConstant.NETWORK_STATE_WIFI);
            Log.d(TAG, "------------------------广告在WIFI情况下不起用弹窗-------------------------");
        }
        TTAdConfig ttAdConfig = builder.build();
        TTAdSdk.init(context, ttAdConfig, new TTAdSdk.InitCallback() {
            @Override
            public void success() {
                Log.d(TAG, "------------------------广告sdk初始化成功-------------------------");
                Log.d(TAG, "------------------------版本号：" + TTAdSdk.getAdManager().getSDKVersion() + "-------------------------");
            }

            @Override
            public void fail(int i, String s) {
                Log.d(TAG, "广告sdk初始化失败：code：" + i + "message：" + s);
            }
        });
    }

    /**
     * 加载开屏广告
     *
     * @param activity
     * @param mSplashContainer 开屏广告view的展示容器
     * @param splashAdId       广告位的id
     * @param splashAdListener 回调监听
     */
    public void loadSplashAd(Activity activity, FrameLayout mSplashContainer, String splashAdId, SplashAdListener splashAdListener) {
        if (!TTAdSdk.isInitSuccess()) {
            Log.e(TAG, "广告sdk未初始化成功");
            if (splashAdListener != null) {
                splashAdListener.jumpToMainScene();
            }
            return;
        }
        if (activity == null) {
            if (splashAdListener != null) {
                splashAdListener.jumpToMainScene();
            }
        }
        Log.e(TAG, "广告版本：" + TTAdSdk.getAdManager().getSDKVersion());
        TTAdNative mTTAdNative = TTAdSdk.getAdManager().createAdNative(activity);
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(splashAdId)
                .setImageAcceptedSize(1080, 1920)
                .build();
        TTAdNative.SplashAdListener listener = new TTAdNative.SplashAdListener() {
            @Override
            public void onError(int code, String message) {
                Log.d(TAG, "<--------------------开屏广告加载失败-------------------->");
                Log.d(TAG, "code------>" + code + "---->message:" + message);
                if (splashAdListener != null) {
                    splashAdListener.jumpToMainScene();
                }
            }

            @Override
            public void onTimeout() {
                Log.d(TAG, "<--------------------开屏广告请求超时-------------------->");
                if (splashAdListener != null) {
                    splashAdListener.jumpToMainScene();
                }
            }

            @Override
            public void onSplashAdLoad(TTSplashAd ad) {
                Log.d(TAG, "开屏广告请求成功");
                if (ad == null) {
                    if (splashAdListener != null) {
                        splashAdListener.jumpToMainScene();
                    }
                    return;
                }
                //获取SplashView
                View view = ad.getSplashView();
                if (activity == null) {
                    return;
                }
                if (mSplashContainer != null && !activity.isFinishing()) {
                    initSplashAdListener(ad, splashAdListener);
                    mSplashContainer.removeAllViews();
                    //把SplashView 添加到ViewGroup中,注意开屏广告view：width >=70%屏幕宽；height >=50%屏幕高
                    mSplashContainer.addView(view);
                    //设置不开启开屏广告倒计时功能以及不显示跳过按钮,如果这么设置，您需要自定义倒计时逻辑
                } else {
                    if (splashAdListener != null) {
                        splashAdListener.jumpToMainScene();
                    }
                }
            }
        };
        mTTAdNative.loadSplashAd(adSlot, listener, adConfig.getSplashAdTimeOut());
    }

    /**
     * 加载开屏广告，使用默认配置AdConfig里配置的开屏广告位的id
     *
     * @param activity
     * @param mSplashContainer
     * @param splashAdListener
     */
    public void loadSplashAd(Activity activity, FrameLayout mSplashContainer, SplashAdListener splashAdListener) {
        loadSplashAd(activity, mSplashContainer, adConfig.getSplashId(), splashAdListener);
    }


    private void initSplashAdListener(TTSplashAd ttSplashAd, SplashAdListener splashAdListener) {
        //设置SplashView的交互监听器
        ttSplashAd.setSplashInteractionListener(new TTSplashAd.AdInteractionListener() {
            @Override
            public void onAdClicked(View view, int type) {

            }

            @Override
            public void onAdShow(View view, int type) {

            }

            @Override
            public void onAdSkip() {
                if (splashAdListener != null) {
                    splashAdListener.jumpToMainScene();
                }

            }

            @Override
            public void onAdTimeOver() {
                if (splashAdListener != null) {
                    splashAdListener.jumpToMainScene();
                }
            }
        });
        if (ttSplashAd.getInteractionType() == TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
            ttSplashAd.setDownloadListener(new TTAppDownloadListener() {
                boolean hasShow = false;

                @Override
                public void onIdle() {
                }

                @Override
                public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
                    if (!hasShow) {
                        hasShow = true;
                    }
                }

                @Override
                public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {

                }

                @Override
                public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {

                }

                @Override
                public void onDownloadFinished(long totalBytes, String fileName, String appName) {

                }

                @Override
                public void onInstalled(String fileName, String appName) {
                }
            });
        }
    }


    /**
     * 加载默认参数的banner广告
     *
     * @param isUseInsideJudge  是否使用内部逻辑来控制广告的展示，当设置为true的时候需要同步设置广告开关状态、用户是否是vip等
     * @param adSwitchStatus    广告开关的状态
     * @param isVip             是否是vip
     * @param activity
     * @param bannerTag         当前广告为的tag，可以自己随意设置，但是在界面销毁时需要传入对应的tag去销毁广告对象，不然会内存泄漏
     * @param mExpressContainer banner广告的容器
     */
    public void loadBannerAd(boolean isUseInsideJudge, boolean adSwitchStatus, boolean isVip, Activity activity, String bannerTag, FrameLayout mExpressContainer) {
        loadBannerAd(isUseInsideJudge, adSwitchStatus, isVip, activity, bannerTag, adConfig.getBannerId(), adConfig.getBannerWidth(), adConfig.getBannerHeight(), mExpressContainer);
    }


    /**
     * 加载banner广告，不受内部任何逻辑控制，加载一次展示一次，显示逻辑需要外部进行控制
     *
     * @param activity
     * @param bannerTag
     * @param mExpressContainer
     */
    public void loadBannerAd(Activity activity, String bannerTag, FrameLayout mExpressContainer) {
        loadBannerAd(false, false, false, activity, bannerTag, adConfig.getBannerId(), adConfig.getBannerWidth(), adConfig.getBannerHeight(), mExpressContainer);
    }


    /**
     * 多广告位加载banner广告时 需要传入广告位id，请求款高等数据
     *
     * @param isUseInsideJudge  是否使用内部逻辑来控制广告的展示，当设置为true的时候需要同步设置广告开关状态、用户是否是vip等
     * @param adSwitchStatus    广告开关的状态
     * @param isVip             是否是vip
     * @param activity
     * @param bannerTag         当前广告为的tag，可以自己随意设置，但是在界面销毁时需要传入对应的tag去销毁广告对象，不然会内存泄漏
     * @param bannerAdId        广告位id
     * @param width             请球宽度
     * @param height            请求高度
     * @param mExpressContainer banner广告的容器
     */
    public void loadBannerAd(boolean isUseInsideJudge, boolean adSwitchStatus, boolean isVip, Activity activity, String bannerTag,
                             String bannerAdId, float width,
                             float height, FrameLayout mExpressContainer) {
        if (activity == null) {
            return;
        }
        if (!isInitSuccess()) {
            return;
        }
        //如果设置使用内部判断，则判断广告开关是否打开，以及是否是vip等
        if (isUseInsideJudge) {
            if (!adSwitchStatus) {
                Log.d(TAG, "广告开关没有打开------------>不加载Banner广告");
                return;
            }
            if (isVip) {
                Log.d(TAG, "用户是Vip------------>不加载Banner广告");
                if (mExpressContainer != null) {
                    mExpressContainer.removeAllViews();
                }
                return;
            }
            if (isLauncherLoadBannerAd) {
                isLauncherLoadBannerAd = false;
            } else {
                if (!canLoadBanner(bannerTag)) {
                    Log.d(TAG, "没有达到广告间隔时间------------>不加载Banner广告");
                    return;
                }
            }
        }
        if (TextUtils.isEmpty(bannerAdId)) {
            return;
        }
        if (activity == null || mExpressContainer == null) {
            return;
        }
        mExpressContainer.removeAllViews();
        //step4:创建广告请求参数AdSlot,具体参数含义参考文档
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(bannerAdId) //广告位id
                .setAdCount(1) //请求广告数量为1到3条
                .setExpressViewAcceptedSize(width, height) //期望模板广告view的size,单位dp
                .build();
        TTAdNative mTTAdNative = TTAdSdk.getAdManager().createAdNative(activity);
        mTTAdNative.loadBannerExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int code, String message) {
                Log.e(TAG, "Banner视频广告加载失败：" + code + "  message:" + message);
                mExpressContainer.removeAllViews();
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                if (ads == null || ads.size() == 0) {
                    return;
                }
                try {
                    if (!activity.isFinishing()) {
                        TTNativeExpressAd bannerTTAD = ads.get(0);
                        bannerTTAD.setSlideIntervalTime(30 * 1000);
                        bindBannerAdListener(activity, bannerTag, mExpressContainer, bannerTTAD);
                        bannerTTAD.render();
                        saveShowBannerTime(bannerTag);
                        bannerMap.put(bannerTag, bannerTTAD);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "banner展示异常：" + e.toString());
                }
            }
        });
    }

    private void bindBannerAdListener(Activity activity, String tag, FrameLayout mExpressContainer, TTNativeExpressAd ad) {
        ad.setExpressInteractionListener(new TTNativeExpressAd.AdInteractionListener() {
            @Override
            public void onAdDismiss() {

            }

            @Override
            public void onAdClicked(View view, int type) {
                // TToast.show(mContext, "广告被点击");
            }

            @Override
            public void onAdShow(View view, int type) {
                // TToast.show(mContext, "广告展示");
            }

            @Override
            public void onRenderFail(View view, String msg, int code) {
                // Log.e("ExpressView", "render fail:" + (System.currentTimeMillis() - startTime));
                // TToast.show(mContext, msg + " code:" + code);
            }

            @Override
            public void onRenderSuccess(View view, float width, float height) {
                //返回view的宽高 单位 dp
                mExpressContainer.removeAllViews();
                mExpressContainer.addView(view);
            }
        });
        ad.setDislikeCallback(activity, new TTAdDislike.DislikeInteractionCallback() {
            @Override
            public void onShow() {

            }

            @Override
            public void onSelected(int i, String s, boolean b) {
                showShort("\t\t\t\t\t\t\t感谢您的反馈!\t\t\t\t\t\t\n我们将为您带来更优质的广告体验");
                mExpressContainer.removeAllViews();
                destroyBanner(tag);
            }


            @Override
            public void onCancel() {
            }

//            @Override
//            public void onRefuse() {
//                showShort("您已成功提交反馈，请勿重复提交哦！");
//            }

        });
        if (ad.getInteractionType() != TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
            return;
        }
        ad.setDownloadListener(new TTAppDownloadListener() {
            @Override
            public void onIdle() {
            }

            @Override
            public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
                if (!mHasShowDownloadActive) {
                    mHasShowDownloadActive = true;
                }
            }

            @Override
            public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {

            }

            @Override
            public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {

            }

            @Override
            public void onInstalled(String fileName, String appName) {

            }

            @Override
            public void onDownloadFinished(long totalBytes, String fileName, String appName) {

            }
        });
    }


    /**
     * 加载开屏广告
     *
     * @param isUseInsideJudge 是否使用内部逻辑来控制广告的展示，当设置为true的时候需要同步设置广告开关状态、用户是否是vip等
     * @param adSwitchStatus   广告开关的状态
     * @param isVip            是否是vip
     * @param activity
     * @param tag
     */
    public void loadInteractionAd(boolean isUseInsideJudge, boolean adSwitchStatus, boolean isVip, Activity activity, String tag) {
        loadInteractionAd(isUseInsideJudge, adSwitchStatus, isVip, activity, adConfig.getInteractionExpressId(), tag, adConfig.getInteractionAdWidth(), adConfig.getInteractionAdHeight());
    }

    /**
     * 加载插屏广告，不受任何控制，调用一次显示一次
     *
     * @param activity
     * @param tag      广告的tag，销毁时要传入一样的tag进行销毁
     */
    public void loadInteractionAd(Activity activity, String tag) {
        loadInteractionAd(false, false, false, activity, adConfig.getInteractionExpressId(), tag, adConfig.getInteractionAdWidth(), adConfig.getInteractionAdHeight());
    }

    /**
     * 加载插屏广告，需要加载多个插屏广告的场景使用
     *
     * @param isUseInsideJudge 是否使用内部逻辑来控制广告的展示，当设置为true的时候需要同步设置广告开关状态、用户是否是vip等
     * @param adSwitchStatus   广告开关的状态
     * @param isVip            是否是vip
     * @param activity         需要显示界面的activity
     * @param interactionAdId  插屏广告的id
     * @param tag              标识当前插屏广告的tag 重要！！！
     * @param width            插屏广告的宽度
     * @param height           插屏广告的高度
     */
    public void loadInteractionAd(boolean isUseInsideJudge, boolean adSwitchStatus, boolean isVip,
                                  Activity activity, String interactionAdId, String tag, float width, float height) {
        if (activity == null) {
            return;
        }
        if (!isInitSuccess()) {
            return;
        }
        if (isUseInsideJudge) {
            if (!adSwitchStatus) {
                Log.d(TAG, "广告开关没有打开------------>不加载插屏广告");
                return;
            }
            if (isVip) {
                Log.d(TAG, "用户是Vip------------>不加载插屏广告");
                return;
            }
            if (isLauncherLoadChaPinAd) {
                isLauncherLoadChaPinAd = false;
            } else {
                if (!canLoadChaPing(tag)) {
                    Log.d(TAG, "没有达到广告间隔时间------------>不加载插屏广告");
                    return;
                }
            }
        }
        TTAdNative mTTAdNative = TTAdSdk.getAdManager().createAdNative(activity);
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(interactionAdId) //广告位id
                .setSupportDeepLink(true)
                .setAdCount(1) //请求广告数量为1到3条
                .setExpressViewAcceptedSize(width, height) //期望模板广告view的size,单位dp
                .build();
        //加载广告
        mTTAdNative.loadInteractionExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int code, String message) {
                Log.e(TAG, "插屏广告加载失败：" + code + "  message:" + message);
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                if (ads == null || ads.size() == 0) {
                    return;
                }
                try {
                    saveShowCpTime(tag);
                    TTNativeExpressAd mTTAd = ads.get(0);
                    mHasShowDownloadActive = false;
                    bindInteractionAdListener(activity, tag, mTTAd);
                    mTTAd.render();//调用render开始渲染广告
                    interactionAdMap.put(tag, mTTAd);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void bindInteractionAdListener(Activity activity, String tag, TTNativeExpressAd ad) {
        ad.setExpressInteractionListener(new TTNativeExpressAd.AdInteractionListener() {
            @Override
            public void onAdDismiss() {
                destroyInteractionAd(tag);
            }

            @Override
            public void onAdClicked(View view, int type) {

            }

            @Override
            public void onAdShow(View view, int type) {

            }

            @Override
            public void onRenderFail(View view, String msg, int code) {

            }

            @Override
            public void onRenderSuccess(View view, float width, float height) {
                ad.showInteractionExpressAd(activity);
            }
        });
        ad.setDislikeCallback(activity, new TTAdDislike.DislikeInteractionCallback() {
            @Override
            public void onShow() {

            }

            @Override
            public void onSelected(int i, String s, boolean b) {
                showShort("\t\t\t\t\t\t\t感谢您的反馈!\t\t\t\t\t\t\n我们将为您带来更优质的广告体验");
            }


            @Override
            public void onCancel() {

            }

        });
        if (ad.getInteractionType() != TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
            return;
        }
        ad.setDownloadListener(new TTAppDownloadListener() {
            @Override
            public void onIdle() {
            }

            @Override
            public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {

            }

            @Override
            public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
            }

            @Override
            public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
            }

            @Override
            public void onInstalled(String fileName, String appName) {
            }

            @Override
            public void onDownloadFinished(long totalBytes, String fileName, String appName) {
            }
        });
    }

    /**
     * 加载默认的广告位id的全屏视频，默认竖屏,默认不需要回调
     * 默认不需要内部控制展示逻辑 比如vip不展示之类的逻辑
     *
     * @param activity
     */
    public void loadFullScreenVideoAd(Activity activity) {
        loadFullScreenVideoAd(false, false, false,
                activity, adConfig.getFullScreenVideoId(), TTAdConstant.VERTICAL, null);
    }

    /**
     * 加载默认广告id的全屏视频广告，默认竖屏需要回调
     *
     * @param isUseInsideJudge 是否使用内部逻辑来控制广告的展示，当设置为true的时候需要同步设置广告开关状态、用户是否是vip等
     * @param adSwitchStatus   广告开关的状态
     * @param isVip            是否是vip
     * @param activity
     * @param listener
     */
    public void loadFullScreenVideoAd(boolean isUseInsideJudge, boolean adSwitchStatus, boolean isVip,
                                      Activity activity, FullScreenVideoAdInteractionListener listener) {
        loadFullScreenVideoAd(isUseInsideJudge, adSwitchStatus, isVip, activity,
                adConfig.getFullScreenVideoId(), TTAdConstant.VERTICAL, listener);
    }

    /**
     * 加载全屏视频广告
     *
     * @param isUseInsideJudge 是否使用内部逻辑来控制广告的展示，当设置为true的时候需要同步设置广告开关状态、用户是否是vip等
     * @param adSwitchStatus   广告开关的状态
     * @param isVip            是否是vip
     * @param activity         activity
     * @param fullAdId         广告位id
     * @param orientation      设置视频的请求方向{@link TTAdConstant#VERTICAL} {@link TTAdConstant#HORIZONTAL}
     * @param listener         视频广告展示操作相关回调
     */
    public void loadFullScreenVideoAd(boolean isUseInsideJudge, boolean adSwitchStatus, boolean isVip,
                                      Activity activity, String fullAdId, int orientation,
                                      FullScreenVideoAdInteractionListener listener) {
        if (activity == null) {
            return;
        }
        if (!isInitSuccess()) {
            return;
        }
        if (isUseInsideJudge) {
            if (!adSwitchStatus) {
                Log.d(TAG, "广告开关没有打开------------>不加载全屏视频广告");
                return;
            }
            if (isVip) {
                Log.d(TAG, "用户是Vip------------>不加载全屏视频广告");
                return;
            }
        }
        TTAdNative mTTAdNative = TTAdSdk.getAdManager().createAdNative(activity);
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(fullAdId)
                .setSupportDeepLink(true)
                .setOrientation(orientation)//必填参数，期望视频的播放方向：TTAdConstant.HORIZONTAL 或 TTAdConstant.VERTICAL
                .build();
        mTTAdNative.loadFullScreenVideoAd(adSlot, new TTAdNative.FullScreenVideoAdListener() {
            //请求广告失败
            @Override
            public void onError(int code, String message) {
                Log.e(TAG, "全屏视频广告加载失败：" + code + "  message:" + message);
                if (listener != null) {
                    listener.onAdLoadError();
                }
            }

            //广告物料加载完成的回调
            @Override
            public void onFullScreenVideoAdLoad(TTFullScreenVideoAd mttFullVideoAd) {
                if (mttFullVideoAd != null) {
                    //展示广告，并传入广告展示的场景
                    if (activity == null || activity.isFinishing()) {
                        return;
                    }
                    mttFullVideoAd.setFullScreenVideoAdInteractionListener(new TTFullScreenVideoAd.FullScreenVideoAdInteractionListener() {
                        @Override
                        public void onAdShow() {
                            if (listener != null) {
                                listener.onAdShow();
                            }
                        }

                        @Override
                        public void onAdVideoBarClick() {
                            if (listener != null) {
                                listener.onAdVideoBarClick();
                            }
                        }

                        @Override
                        public void onAdClose() {
                            if (listener != null) {
                                listener.onAdClose();
                            }
                        }

                        @Override
                        public void onVideoComplete() {
                            if (listener != null) {
                                listener.onVideoComplete();
                            }
                        }

                        @Override
                        public void onSkippedVideo() {
                            if (listener != null) {
                                listener.onSkippedVideo();
                            }
                        }
                    });
                    mttFullVideoAd.showFullScreenVideoAd(activity, TTAdConstant.RitScenes.GAME_GIFT_BONUS, null);
                    mttFullVideoAd = null;
                }
            }

            //广告视频本地加载完成的回调，接入方可以在这个回调后直接播放本地视频
            @Override
            public void onFullScreenVideoCached() {

            }

            @Override
            public void onFullScreenVideoCached(TTFullScreenVideoAd ttFullScreenVideoAd) {

            }
        });

    }

    /**
     * 加载激励视频广告 部分参数传递默认的
     *
     * @param activity
     * @param listener
     */
    public void loadRewardVideoAd(Activity activity, RewardAdInteractionListener listener) {
        loadRewardVideoAd(activity, adConfig.getRewardVideoId(), TTAdConstant.VERTICAL,
                "", "", "", 0, listener);
    }


    /**
     * 加载激励视频广告  需要传递一些详细参数，
     *
     * @param activity
     * @param rewardAdId  广告位id
     * @param orientation 展示方向{@link TTAdConstant#VERTICAL} 和{@link TTAdConstant#HORIZONTAL}
     * @param userId      如果需要验证奖励 则需要设置
     * @param media_extra 附加参数 验证奖励使用，不验证可以传空
     * @param rewardName  奖励或奖品的名称 验证奖励使用，不验证可以传空
     * @param count       奖品数量
     * @param listener    回调
     */
    public void loadRewardVideoAd(Activity activity, String rewardAdId,
                                  int orientation, String userId, String media_extra,
                                  String rewardName, int count, RewardAdInteractionListener listener) {
        if (activity == null) {
            if (listener != null) {
                listener.onAdLoadError();
            }
            return;
        }
        if (!isInitSuccess()) {
            if (listener != null) {
                listener.onAdLoadError();
            }
            return;
        }
        TTAdNative mTTAdNative = TTAdSdk.getAdManager().createAdNative(activity);
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(rewardAdId)
                .setRewardName(TextUtils.isEmpty(userId) ? "default" : rewardName) //奖励的名称 选填
                .setRewardAmount(count)  //奖励的数量 选填
                .setUserID(TextUtils.isEmpty(userId) ? "default" : userId)//tag_id
                .setMediaExtra(media_extra) //附加参数
                .setOrientation(orientation) //必填参数，期望视频的播放方向：TTAdConstant.HORIZONTAL 或 TTAdConstant.VERTICAL
                .build();
        mTTAdNative.loadRewardVideoAd(adSlot, new TTAdNative.RewardVideoAdListener() {
            //请求广告失败
            @Override
            public void onError(int code, String message) {
                Log.e(TAG, "激励视频广告加载失败：" + code + "  message:" + message);
                if (listener != null) {
                    listener.onAdLoadError();
                }
            }

            //视频广告加载后，视频资源缓存到本地的回调，在此回调后，播放本地视频，流畅不阻塞。
            @Override
            public void onRewardVideoCached() {

            }

            @Override
            public void onRewardVideoCached(TTRewardVideoAd ttRewardVideoAd) {

            }

            //视频广告的素材加载完毕，比如视频url等，在此回调后，可以播放在线视频，网络不好可能出现加载缓冲，影响体验。
            @Override
            public void onRewardVideoAdLoad(TTRewardVideoAd mttRewardVideoAd) {
                if (mttRewardVideoAd != null) {
                    //展示广告，并传入广告展示的场景
                    mttRewardVideoAd.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {
                        @Override
                        public void onAdShow() {
                            if (listener != null) {
                                listener.onAdShow();
                            }
                        }

                        @Override
                        public void onAdVideoBarClick() {
                            if (listener != null) {
                                listener.onAdVideoBarClick();
                            }
                        }

                        @Override
                        public void onAdClose() {
                            if (listener != null) {
                                listener.onAdClose();
                            }
                        }

                        @Override
                        public void onVideoComplete() {
                            if (listener != null) {
                                listener.onVideoComplete();
                            }
                        }

                        @Override
                        public void onVideoError() {
                            if (listener != null) {
                                listener.onVideoError();
                            }
                        }

                        @Override
                        public void onRewardVerify(boolean rewardVerify, int rewardAmount, String rewardName, int code, String msg) {
                            if (listener != null) {
                                listener.onRewardVerify(rewardVerify, rewardAmount, rewardName, code, msg);
                            }
                        }

                        @Override
                        public void onSkippedVideo() {
                            if (listener != null) {
                                listener.onSkippedVideo();
                            }
                        }
                    });
                    if (activity == null || activity.isFinishing()) {
                        return;
                    }
                    mttRewardVideoAd.showRewardVideoAd(activity, TTAdConstant.RitScenes.CUSTOMIZE_SCENES, "scenes_test");
                    mttRewardVideoAd = null;
                } else {
                    if (listener != null) {
                        listener.onAdLoadError();
                    }
                }
            }
        });
    }


    /**
     * 销毁对应的banner广告对象
     * 在ondestroy中调用
     *
     * @param tag
     */
    public void destroyBanner(String tag) {
        try {
            if (TextUtils.isEmpty(tag)) {
                return;
            }
            if (bannerMap.containsKey(tag)) {
                TTNativeExpressAd ad = bannerMap.get(tag);
                if (ad != null) {
                    ad.destroy();
                }
                bannerMap.remove(tag);
                Log.d(TAG, "--------------------移除TAG为" + tag + "的banner广告了--------------------");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 销毁对应的插屏广告对象
     * 在ondestroy中调用
     *
     * @param tag
     */
    public void destroyInteractionAd(String tag) {
        try {
            if (TextUtils.isEmpty(tag)) {
                return;
            }
            if (interactionAdMap.containsKey(tag)) {
                TTNativeExpressAd ad = interactionAdMap.get(tag);
                if (ad != null) {
                    ad.destroy();
                }
                interactionAdMap.remove(tag);
                Log.d(TAG, "--------------------移除TAG为" + tag + "的插屏广告了--------------------");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 广告位参数构造器
     */
    public static class AdConfigBuilder {
        /**
         * 广告媒体的id
         */
        private String adAppId = "";
        /**
         * 开屏广告位id
         */
        private String splashId = "";
        /**
         * 插屏广告位id
         */
        private String interactionExpressId = "";
        /**
         * banner广告的广告位id
         */
        private String bannerId = "";
        /**
         * 全屏视频的广告位id
         */
        private String fullScreenVideoId = "945897476";
        /**
         * 激励视频的广告位id
         */
        private String rewardVideoId = "945897478";

        /**
         * banner广告的的宽度 单位dp，根据后台广告位选择的尺寸来进行配置，
         * 不配置则默认为600，但可能会显示有问题
         */
        private float bannerWidth = 600;
        /**
         * banner广告的的高度 单位dp，根据后台广告位选择的尺寸来进行配置，
         * 不配置则默认为90，但可能会显示有问题
         */
        private float bannerHeight = 90;

        /**
         * 插屏广告的的宽度 单位dp，根据后台广告位选择的尺寸来进行配置，
         * 不配置则默认为300，但可能会显示有问题
         */
        private float interactionAdWidth = 300;
        /**
         * 插屏广告的的高度 单位dp，根据后台广告位选择的尺寸来进行配置，
         * 不配置则默认为450，但可能会显示有问题
         */
        private float interactionAdHeight = 450;


        /**
         * 插屏广告的间隔时间默认为180s 也就是主页重现后，单位秒
         * 需要判断和上一次展示广告的时间是否大于了设置的值 是则重新请求广告
         */
        private int interactionIntervalTime = 150;

        /**
         * 在banner被用户手动关闭后，间隔三分钟重新触发banner广告进行展示
         */
        private int bannerIntervalTime = 180;

        /**
         * 开屏广告加载的超时时间 默认为3秒钟，单位为毫秒
         */
        private int splashAdTimeOut = 3000;

        /**
         * 是否启用任何网络下都弹出广告弹窗提醒
         */
        private boolean enablePopDialogWithAd = false;


        public AdConfigBuilder setAdAppId(String adAppId) {
            this.adAppId = adAppId;
            return this;
        }

        public AdConfigBuilder setSplashId(String splashId) {
            this.splashId = splashId;
            return this;
        }

        public AdConfigBuilder setInteractionExpressId(String interactionExpressId) {
            this.interactionExpressId = interactionExpressId;
            return this;
        }

        public AdConfigBuilder setBannerId(String bannerId) {
            this.bannerId = bannerId;
            return this;
        }

        public AdConfigBuilder setFullScreenVideoId(String fullScreenVideoId) {
            this.fullScreenVideoId = fullScreenVideoId;
            return this;
        }

        public AdConfigBuilder setRewardVideoId(String rewardVideoId) {
            this.rewardVideoId = rewardVideoId;
            return this;
        }

        public AdConfigBuilder setBannerHeight(float bannerHeight) {
            this.bannerHeight = bannerHeight;
            return this;
        }

        public AdConfigBuilder setBannerWidth(float bannerWidth) {
            this.bannerWidth = bannerWidth;
            return this;
        }

        public AdConfigBuilder setInteractionAdWidth(float interactionAdWidth) {
            this.interactionAdWidth = interactionAdWidth;
            return this;
        }

        public AdConfigBuilder setInteractionAdHeight(float interactionAdHeight) {
            this.interactionAdHeight = interactionAdHeight;
            return this;
        }


        /**
         * 设置插屏广告显示的间隔时间
         *
         * @param interactionIntervalTime
         * @return
         */
        public AdConfigBuilder setInteractionIntervalTime(int interactionIntervalTime) {
            this.interactionIntervalTime = interactionIntervalTime;
            return this;
        }

        /**
         * 设置banner广告被关闭后重新展示的间隔时间
         *
         * @param bannerIntervalTime
         * @return
         */
        public AdConfigBuilder setBannerIntervalTime(int bannerIntervalTime) {
            this.bannerIntervalTime = bannerIntervalTime;
            return this;
        }

        /**
         * 设置开屏广告的超时时间
         *
         * @param splashAdTimeOut
         * @return
         */
        public AdConfigBuilder setSplashAdTimeOut(int splashAdTimeOut) {
            this.splashAdTimeOut = splashAdTimeOut;
            return this;
        }

        public AdConfigBuilder setEnablePopDialogWithAd(boolean enablePopDialogWithAd) {
            this.enablePopDialogWithAd = enablePopDialogWithAd;
            return this;
        }


        public AdConfig builder() {
            return new AdConfig(this);
        }

        protected String getAdAppId() {
            return adAppId;
        }

        protected String getSplashId() {
            return splashId;
        }

        protected String getInteractionExpressId() {
            return interactionExpressId;
        }

        protected String getBannerId() {
            return bannerId;
        }

        protected String getFullScreenVideoId() {
            return fullScreenVideoId;
        }

        protected String getRewardVideoId() {
            return rewardVideoId;
        }

        protected float getBannerWidth() {
            return bannerWidth;
        }

        protected float getBannerHeight() {
            return bannerHeight;
        }

        protected float getInteractionAdWidth() {
            return interactionAdWidth;
        }

        protected float getInteractionAdHeight() {
            return interactionAdHeight;
        }

        protected int getInteractionIntervalTime() {
            return interactionIntervalTime;
        }

        protected int getBannerIntervalTime() {
            return bannerIntervalTime;
        }

        protected int getSplashAdTimeOut() {
            return splashAdTimeOut;
        }

        public boolean isEnablePopDialogWithAd() {
            return enablePopDialogWithAd;
        }
    }


    public boolean canLoadChaPing(String tag) {
        if (sharedPreferences == null) {
            return true;
        }
        String keyTag = LOAD_CHAPIN + tag;
        long saveTime = sharedPreferences.getLong(keyTag, 0);
        long currentTime = System.currentTimeMillis();
        long chazhi = (currentTime - saveTime) / 1000;//秒数
        if (chazhi >= adConfig.getInteractionIntervalTime()) {
            Log.d(TAG, "当前tag为：" + keyTag + "的时间差值大于" + adConfig.getInteractionIntervalTime() + "秒钟显示广告------》" + chazhi);
            return true;
        } else {
            Log.d(TAG, "当前tag为：" + keyTag + "的时间差值小于" + adConfig.getInteractionIntervalTime() + "秒钟不显示广告------》" + chazhi);
            return false;
        }
    }

    public boolean canLoadBanner(String tag) {
        if (sharedPreferences == null) {
            return true;
        }
        String keyTag = LOAD_BANNER + tag;
        long saveTime = sharedPreferences.getLong(keyTag, 0);
        long currentTime = System.currentTimeMillis();
        long chazhi = (currentTime - saveTime) / 1000;//秒数
        if (chazhi >= adConfig.getBannerIntervalTime()) {
            Log.d(TAG, "当前tag为：" + keyTag + "的时间差值大于" + adConfig.getBannerIntervalTime() + "秒钟显示Banner广告------》" + chazhi);
            return true;
        } else {
            Log.d(TAG, "当前tag为：" + keyTag + "的时间差值小于" + adConfig.getBannerIntervalTime() + "秒钟不显示Banner广告------》" + chazhi);
            return false;
        }
    }


    /**
     * 更新插屏加载时间
     *
     * @return
     */
    public void saveShowBannerTime(String tag) {
        if (sharedPreferences != null) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putLong(LOAD_BANNER + tag, System.currentTimeMillis());
            editor.commit();
        }
    }


    /**
     * 更新插屏加载时间
     *
     * @return
     */
    public void saveShowCpTime(String tag) {
        if (sharedPreferences != null) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putLong(LOAD_CHAPIN + tag, System.currentTimeMillis());
            editor.commit();
        }
    }


    /**
     * 开屏广告监听器
     */
    public interface SplashAdListener {

        /**
         * 广告逻辑执行完毕后跳转主界面
         */
        void jumpToMainScene();

    }


    /**
     * 全屏视频广告相关的回调
     */
    public interface FullScreenVideoAdInteractionListener {

        void onAdLoadError();

        void onAdShow();

        void onAdVideoBarClick();

        void onAdClose();

        void onVideoComplete();

        void onSkippedVideo();
    }

    /**
     * 激励视频广告相关的回调
     */
    public interface RewardAdInteractionListener {

        void onAdLoadError();

        void onAdShow();

        void onAdVideoBarClick();

        void onAdClose();

        /**
         * 视频播放完毕时回调 点击跳过是不回调的
         */
        void onVideoComplete();

        void onVideoError();

        /**
         * 这里可以判断是否让用户使用功能等 视频如果看了3/4以上，不用看完也是可以发放奖励的
         *
         * @param rewardVerify 是否发放奖励或者使用功能
         * @param rewardAmount
         * @param rewardName
         * @param code
         * @param msg
         */
        void onRewardVerify(boolean rewardVerify, int rewardAmount, String rewardName, int code, String msg);

        void onSkippedVideo();
    }

    private void showShort(String content) {
        Toast.makeText(context, content, Toast.LENGTH_SHORT).show();
    }

}
